"""
模型管理服务
负责大模型的配置和管理
"""

from typing import List, Optional, Dict, Any
from sqlalchemy.orm import Session
from sqlalchemy import and_

from app.models.model_config import ModelConfig
from app.services.base_service import BaseService
from app.schemas.model_config import ModelConfigCreate, ModelConfigUpdate


class ModelService(BaseService[ModelConfig, ModelConfigCreate, ModelConfigUpdate]):
    """模型配置服务"""
    
    def __init__(self):
        super().__init__(ModelConfig)
    
    def get_active_models(self, db: Session) -> List[ModelConfig]:
        """获取所有激活的模型配置"""
        return db.query(ModelConfig).filter(ModelConfig.is_active == True).all()
    
    def get_default_model(self, db: Session) -> Optional[ModelConfig]:
        """获取默认模型配置"""
        return db.query(ModelConfig).filter(
            and_(
                ModelConfig.is_default == True,
                ModelConfig.is_active == True
            )
        ).first()
    
    def get_models_by_provider(self, db: Session, provider: str) -> List[ModelConfig]:
        """根据提供商获取模型配置"""
        return db.query(ModelConfig).filter(
            and_(
                ModelConfig.provider == provider,
                ModelConfig.is_active == True
            )
        ).all()
    
    def set_default_model(self, db: Session, model_id: int) -> bool:
        """设置默认模型"""
        # 先取消所有默认设置
        db.query(ModelConfig).update({"is_default": False})
        
        # 设置新的默认模型
        model = db.query(ModelConfig).filter(ModelConfig.id == model_id).first()
        if model:
            model.is_default = True
            db.commit()
            return True
        return False
    
    def test_model_connection(self, model_config: ModelConfig) -> Dict[str, Any]:
        """测试模型连接"""
        try:
            # 这里应该根据不同的提供商实现连接测试
            # 暂时返回模拟结果
            return {
                "success": True,
                "message": "连接测试成功",
                "response_time": 0.5
            }
        except Exception as e:
            return {
                "success": False,
                "message": f"连接测试失败: {str(e)}",
                "response_time": None
            }
    
    def get_model_info(self, model_config: ModelConfig) -> Dict[str, Any]:
        """获取模型信息"""
        return {
            "id": model_config.id,
            "name": model_config.name,
            "provider": model_config.provider,
            "model_name": model_config.model_name,
            "base_url": model_config.base_url,
            "temperature": model_config.temperature,
            "max_tokens": model_config.max_tokens,
            "is_active": model_config.is_active,
            "is_default": model_config.is_default,
            "description": model_config.description,
            "created_at": model_config.created_at,
            "updated_at": model_config.updated_at
        }
